package net.oschina.git.hikoyan.helloapi.controller;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import net.oschina.git.hikoyan.helloapi.openoffice.OpenOfficeContext;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.document.DocumentFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by yan on 16/11/28.
 */
@RestController
@Api(value = "converter-api", description = "office转换pdf")
public class ConverterController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/converter/{outputExtension}", method = RequestMethod.POST)
    @ApiOperation(value = "转换文件", httpMethod = "POST", notes = "转换文件")
    public void converter(@ApiParam(name = "inputDocument", value = "上传文件") @RequestParam(value = "inputDocument") MultipartFile file,
                          @ApiParam(name = "outputExtension", value = "转换后文件扩展名") @PathVariable("outputExtension") String outputExtension,
                          @ApiParam(name = "response", value = "response") HttpServletResponse response) throws IOException {
        if (!file.isEmpty()) {
            String inputExtension = FilenameUtils.getExtension(file.getOriginalFilename());
            String baseName = FilenameUtils.getBaseName(file.getOriginalFilename());
            File inputFile = File.createTempFile(baseName, "." + inputExtension);
            File outputFile = File.createTempFile(baseName, "." + outputExtension);
            try {
                file.transferTo(inputFile);
                OfficeDocumentConverter converter = OpenOfficeContext.getDocumentConverter();
                DocumentFormat outputFormat = converter.getFormatRegistry().getFormatByExtension(outputExtension);
                long startTime = System.currentTimeMillis();
                converter.convert(inputFile, outputFile);
                long conversionTime = System.currentTimeMillis() - startTime;
                logger.info(String.format("successful conversion: %s [%db] to %s in %dms", inputExtension, inputFile.length(), outputExtension, conversionTime));
                response.setContentType(outputFormat.getMediaType());
                //new String(baseName.getBytes(), "ISO-8859-1") 中文文件名需转码
                response.setHeader("Content-Disposition", "attachment; filename=" + new String(baseName.getBytes(), "ISO-8859-1") + "." + outputExtension);
                sendFile(outputFile, response);
            } catch (IOException e) {
                logger.error(getClass().getName(), e);
            } finally {
                outputFile.delete();
                inputFile.delete();
            }
        }
    }

    private void sendFile(File file, HttpServletResponse response) throws IOException {
        response.setContentLength((int) file.length());
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            IOUtils.copy(inputStream, response.getOutputStream());
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

}
